const { Controller } = require('varal');
const { sequelize } = require('../../models');
const { QueryTypes } = require('sequelize');

const dayjs = require('dayjs');
const chance = require('chance').Chance();
const path = require('path');
const fs = require('fs');

class UtilController extends Controller {
	async upload() {
		const { files } = this.app;
		const file = files[0];

		//保存文件
		const dir = dayjs().format('YYYYMM');

		const uploadDir = path.resolve('public/uploadfile', dir);
		console.log(__dirname, __filename, uploadDir);


		//判断目录是否存在
		if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir);

		const filename = `${chance.string({ length: 32, alpha: true, numeric: true })}${path.extname(file.originalFilename)}`;

		fs.writeFileSync(path.join(uploadDir, filename), fs.readFileSync(file.path));
		const url = `https://mp.kachewo.com/uploadfile/${dir}/${filename}`;

		return this.app.json({
			err_code: 0,
			data: {
				url
			}
		});
	}
}

exports = module.exports = UtilController;
